<template>

<div class="translation" curPageName="sfsadf2342454223333222">

    <!-- <div class="grid_box">
	<div class="left">
        <grid-layout ref="gridLayout" v-model:layout="layout" :col-num="12" :row-height="30" :is-draggable="true" :is-resizable="true" :is-mirrored="false" :vertical-compact="true" :margin="[10, 10]" :use-css-transforms="true">
            <grid-item style="border:1px solid #000" ref="gridItem" @resized="resizedEvent" v-for="item in layout" :x="item.x" :y="item.y" :w="item.w" :h="item.h" :i="item.i" :key="item.i">
                <span class=" close" @click="delItem(item)"><i class="iconfont icon-guanbi"></i></span>
                    {{item.i}}
            </grid-item>
        </grid-layout>

	</div>
</div> -->


    <div class="merak-card merak-container-has-search" v-waterMarker>

    <!-- <div @click="getFileDataFun()">获取给后台的值</div>
    <uploadFileMerak ref="fileMerakRef" v-model="fileList" :postImage='"file"' :path="Path.certify"></uploadFileMerak> -->

        <!-- 搜索模块儿 -->
        <div>
            <serachBar custom_class="myclass" 
                    :close-plan="true"
                    :close-advanced="true"
                    :placeholder='$t("archive_set_qifacolor.colorname")' :search_val=search_val
                    @search-event="searchFn">
                        <template #footer>
                            <!-- // 权限03 -->
                            <el-button  v-auth="{ authArr: authArr, key: 'addColor' }"  @click="onPlus()"  type="primary" >{{$t("archive_set_qifacolor.add")}}
						</el-button>
                        </template>
                    </serachBar>
        
        </div>
        <div class="merak-table-wrapper">
            <MerakXTable ref="tableRef" :columns-by-store="JSON.parse(JSON.stringify(state.columns))"
                        :query-columns="handleQueryColumns" :query-data="handleQueryData" :params="state.params"
                        :pictureExport="true"
                        :column-type="columnTypeAuth"
                        :batches="[]"
                        :batch-click="handleBatchClick">
                        <template #handler="{ row }">
                            <div>
                                <!-- // 权限04 v-auth="{'authArr':authArr,'key':'edit'}"  -->
                                <el-button type="primary" link  v-auth="{ authArr: authArr, key: 'editColor' }"  @click="saveEdit(row)"> {{$t("manage_set.edit_manage_set")}} </el-button>
                                
                                <el-button v-auth="{ authArr: authArr, key: 'delColor' }" type="default" v-if="row.is_disable==true" disabled link> 删除 </el-button>
                                <el-button v-auth="{ authArr: authArr, key: 'delColor' }" v-else  type="danger" link    @click="delTranslation(row)"> 删除 </el-button>
                                
                                
                            
                            </div>
                        </template>

                        <template #color="{ row }">
                            <div style="width:30px;height:30px;overflow:hidden;border-radius:4px;">
                                <img style="width:100%;" :src="row.color_image">
                            </div>
                           
                        </template>


                        

                    </MerakXTable>
        </div>
    </div>


    <el-drawer modal-class="merak_modal manage_drawer"  v-model="drawerTranslation" direction="rtl" size="30%">
            
            <template #header>
                <div class="merak_modal_title">{{translationTitle}}</div>
            </template>
        
            <div class="form-box">
                <div  >
                    <el-form :model="setForm" ref="setRef" :rules="translationRules"
                        label-position="top">

                        <el-form-item :label='$t("archive_set_qifacolor.color_ru")' prop="color_ru">
                                    <el-input maxlength="50" class="qf_input" v-model="setForm.color_ru" />
                                </el-form-item>
                                
                                <el-form-item :label='$t("archive_set_qifacolor.color_cn")' prop="color_cn">
                                    <el-input maxlength="100" class="qf_input" v-model="setForm.color_cn" />
                                </el-form-item>

                        
                          
                                <el-form-item :label='$t("archive_set_qifacolor.sort")'  prop="sort">
                                    <el-input  v-number class="qf_input" v-model="setForm.sort" />

                                </el-form-item>
                                      <el-form-item :label='$t("archive_set_qifacolor.color_image")'  prop="color_image">
                                    <uploadOneImg :postImage='"color_image"' v-model="setForm.color_image"  :request="handleRequestInfo"></uploadOneImg>
                                    <div class="form_tooltip">请上传100kb内, 100 X 100大小的色卡</div>
                                </el-form-item>
                    </el-form>
                </div>

            </div>

            <template #footer>
                <el-button v-if="editShow==false" type="default" @click="cancelEmpty(setRef)">{{$t("merak.cancel")}}</el-button>
                <el-button type="primary" plain v-if="editShow"
                    @click="saveContinue('2',setRef)">{{$t("merak.save_continue")}}</el-button>
                <el-button type="primary" @click="submitForm('1',setRef)">{{$t("merak.save")}}</el-button>

            </template>
        </el-drawer>

</div>























</template>

<script lang="ts" setup name="qifaColor">
    import { Plus, Edit, Delete, EditPen } from '@element-plus/icons-vue';

    import { ref, reactive, onMounted, getCurrentInstance } from "vue";
    import serachBar from "@/components/SearchBar/index";
    import MerakXTable, { MerakXTableInstance, MerakXTableColumn, MerakXTableQuery } from "@/components/MerakXTable";
    import { moreConfirm, confirmWarningMsg, successMsg, warnMsg, failMsg, confirmSuccessMsg, delConfimMsg } from "@/utils/messageUtils";
	import { getSetHeadApi, getSetListApi ,saveCreateSet ,saveEditSet ,delSet} from "@/api/modules/goodsArchive/set/qifaColor";
    import I18n from "@/languages/index";
    import uploadOneImg from "@/components/uploadOneImg/index.vue";

  



   
    import uploadFileMerak from "@/components/uploadFileMerak/index.vue";

    import {uploadFiles} from "@/api/modules/goodsArchive/set/qifaColor";


    import {Path} from "@/api/modules/upload";
    

    import type { ElForm } from "element-plus";
    type FormInstance = InstanceType<typeof ElForm>;
    const setRef = ref < FormInstance > ();

    const { proxy } = getCurrentInstance();

    const  fileMerakRef=ref(null);
    const fileList=ref([
  {
    size: 49489,
    type: 'jpeg',
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
  {
    size: 49489,
    type: 'jpeg',
    name: 'food2.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
])



const getFileDataFun = async (e) => {
    console.log(fileMerakRef.value.getFileData())
    

}

const layout = ref([
        { "x": 0, "y": 0, "w": 2, "h": 2, "i": "0" },
        { "x": 2, "y": 0, "w": 2, "h": 4, "i": "1" },
        { "x": 4, "y": 0, "w": 2, "h": 5, "i": "2" },
        { "x": 6, "y": 0, "w": 2, "h": 3, "i": "3" },
        { "x": 8, "y": 0, "w": 2, "h": 3, "i": "4" },
        { "x": 10, "y": 0, "w": 2, "h": 3, "i": "5" },
        { "x": 0, "y": 5, "w": 2, "h": 5, "i": "6" },
        { "x": 2, "y": 5, "w": 2, "h": 5, "i": "7" },
        { "x": 4, "y": 5, "w": 2, "h": 5, "i": "8" },
        { "x": 6, "y": 3, "w": 2, "h": 4, "i": "9" },
        { "x": 8, "y": 4, "w": 2, "h": 4, "i": "10" }])




const gridLeftRef = ref<any>()
const gridRightRef = ref<any>()

const layoutLeft = ref([
	{ i: '1', x: 0, y: 0, w: 2, h: 2 },
	{ i: '2', x: 2, y: 0, w: 2, h: 2 },
	{ i: '3', x: 0, y: 0, w: 2, h: 2 },
	{ i: '4', x: 2, y: 0, w: 2, h: 2 }
])

const layoutRight = ref([
	{ i: '1', x: 0, y: 0, w: 2, h: 2 },
	{ i: '2', x: 2, y: 0, w: 2, h: 2 },
	{ i: '3', x: 0, y: 0, w: 2, h: 2 },
	{ i: '4', x: 2, y: 0, w: 2, h: 2 }
])

// 处理Grid同步
const handleGridSync = () => {
	layoutLeft.value.forEach((item1) => {
		layoutRight.value.forEach((item2) => {
			if (item1.i === item2.i) {
				item2.x = item1.x
				item2.y = item1.y
				item2.w = item1.w
				item2.h = 2
			}
		})
	})
	gridLeftRef.value.layoutUpdate()
	gridLeftRef.value.updateHeight()
	gridRightRef.value.layoutUpdate()
	gridRightRef.value.updateHeight()
}

// 创造Grid
const createGrid = () => {
	let maxH = 0
	layoutLeft.value.forEach((item) => {
		if (item.y > maxH) maxH = item.y
	})
	const uid = createUuid()
	layoutLeft.value.push({ i: uid, x: 0, y: maxH, w: 2, h: 2 })
	layoutRight.value.push({ i: uid, x: 0, y: maxH, w: 2, h: 2 })
	handleGridSync()
}

// 删除Grid
const deleteGrid = (id: string) => {
	const idx1 = layoutLeft.value.findIndex((item1) => item1.i === id)
	layoutLeft.value.splice(idx1, 1)
	const idx2 = layoutRight.value.findIndex((item2) => item2.i === id)
	layoutRight.value.splice(idx2, 1)
	handleGridSync()
}

   
  


    const tableRef = ref < MerakXTableInstance > ();
    const $t = I18n.global.t;

	const color = ref('rgba(255, 69, 0, 0.68)')
		const predefineColors = ref([
		'#E63415',
		'#FF6600',
		'#FFDE0A',
		'#1EC79D',
		'#14CCCC',
		'#4167F0',
		'#6222C9'
		
		])


 const handleRequestInfo = async (options, type) => {
  console.log(options)

  const formData = new FormData();
  formData.append(options.filename, options.file);
  uploadFiles(formData, evt => {
    console.log(evt)
    options.onProgress(evt);
  })
    .then(({ code, data, message }) => {
      if (code == ResultEnum.SUCCESS) {
        console.log(data)
        options.onSuccess(data);




        
      } else {
        // @ts-ignore
        options.onError({ message: message });
      }
    })
    .catch(err => {
      options.onError(err);
    });
};
















    //批量操作
    const handleBatchClick = async (e) => {
        console.log(e)

    }


    //#region 搜索表单
    let search_val = ref("");
	//触发了快速搜索或者搜索方案
	const searchFn = params => {
	console.log(params)
	let postParams = { ...params.params,  keyword: params.search  };
	state.params = postParams;
	};

    //#endregion



    //#region 新增、编辑、删除
    const drawerTranslation = ref(false);
    const translationTitle = ref("新增企发颜色");
    translationTitle.value=$t("archive_set_qifacolor.add")
    //表单参数结构
    const setForm = ref ({
		qifa_color_id:0,
        color_ru: "",
        color_cn: "",
        color_image: "",
        sort: "",
    })
	const validateDay = (rule: any, value: any, callback: any) => {
        if (value === '') {
            callback(new Error(proxy.$t("main.requiredMsg")))
        } else {
			let reg = /^-?(0|([1-9][0-9]*))(\.[\d]+)?$/;
            if (reg.test(value)) {

            } else {
                callback(new Error("必须数字"))
            }
            callback()
        }
    };
    const translationRules = reactive({
        
		color_ru: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
		color_cn: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
		color_image: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
		sort: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
    });


    
	const resetForm = (formEl: FormInstance | undefined) => {
	  if (!formEl) return
	  formEl.resetFields()
	}
    //新增操作
    const onPlus = () => {
        editShow.value = true;
        setForm.value = {
            qifa_color_id:0,
            color_ru: "",
            color_cn: "",
            color_image: "",
            sort: "",
            }
		
		resetForm(setRef.value)
        //打开弹窗
        drawerTranslation.value = true;



    };
    //保存并继续
    const saveContinue = (typebtn: string, formEl: FormInstance | undefined) => {
        submitForm(typebtn, formEl)
    }

    const submitForm = async (typebtn: string, formEl: FormInstance | undefined) => {
        if (!formEl) return;
        await formEl.validate((valid, fields) => {
            if (valid) {
                //保存
              
                postAdd(typebtn, formEl);
                console.log("submit!");
            } else {
                
                console.log("error submit!", fields);
            }
        });
    };
    //新增  
    /**
     * typebtn 1保存 2保存并继续
    */
    const postAdd = (typebtn: string, formEl: FormInstance | undefined) => {
        if (editShow.value) {
            //新增

           

            }


            var setFormNew= JSON.parse(JSON.stringify(setForm.value))
            console.log(setFormNew)
            if(setFormNew){
                var longurl = setFormNew.color_image;
                    longurl = '/' + longurl.split('/').slice(3).join('/');
                    console.log(longurl)
                    setFormNew.color_image=longurl;

                  
            saveCreateSet(setFormNew).then(res => {
                console.log(res)
                if (res.code == ResultEnum.SUCCESS) {
                    successMsg('保存成功!');
                    if (typebtn == 1) {
                        //关闭弹窗
                        drawerTranslation.value = false;
                        //formEl.resetFields();
                    } else {
                        let resetObj = {
							qifa_color_id:0,
                            color_ru: "",
                            color_cn: "",
                            color_image: "",
                            sort: "",
                          
                        }
                        setForm.value= { ...setForm.value, ...resetObj }
                      
					   resetForm(setRef.value)
                    }

                    tableRef.value?.reloadData();
                }else{
					failMsg(res.message);
				}
                
            }, err => {
                console.log(err)
            })

        } else {
            //编辑
            saveEditSet(setForm.value).then(res => {
                if (res.code == ResultEnum.SUCCESS) {
                    successMsg('编辑成功!');
                    //关闭弹窗
                    drawerTranslation.value = false;
                    // formEl.resetFields();
                    tableRef.value?.reloadData();
                }else {
                    failMsg(res.message);
                }
            }, err => {
                console.log(err)
            })
        }



    }

    //编辑
    let editShow = ref(true);
    const saveEdit = (row: setForm) => {
        
		const rowt = JSON.parse(JSON.stringify(row))
		setForm.value = rowt;
        //打开弹窗
        drawerTranslation.value = true;
        editShow.value = false;
       translationTitle.value=$t("archive_set_qifacolor.edit")

    }

    //取消
    const cancelEmpty = (formEl: FormInstance | undefined) => {
        if (!formEl) return;
        formEl.resetFields();
        drawerTranslation.value = false;
    }



    //删除
    const delTranslation = (row: setForm) => {
        delConfimMsg({
            callback: val => {
                if (val == "confirm") {
                    delOne(row);
                }
            }
        });
    }

    const delOne = (row: setForm) => {
        delSet({ qifa_color_id: row.qifa_color_id }).then(res => {

            if (res.code == ResultEnum.SUCCESS) {
                successMsg('删除成功!');
                setTimeout(() => {
                    tableRef.value?.reloadData();
                }, 500)
                }else {
                    failMsg(res.message);
                }

           





        })
    }
    //#endregion

    const state = reactive < {
        params: Record < string, any>;
    columns: MerakXTableColumn[];
    } > ({
        params: {
            key_words: ""
        },
        columns: []
    });

    //权限01数据
    let authArr = ref({});



	const columnTypeAuth= reactive([]);





    if($t("lang")=='ru'){
        Object.assign(columnTypeAuth, [{type: 'handle', width: 280, slot: 'handler' }]);
    }else{
        Object.assign(columnTypeAuth,  [{type: 'handle', width: 120, slot: 'handler' }]);
    }





    //列表内容展示区
    const handleQueryData: MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => {
        const params: Record<string, any> = {};
			if (!!page) {
            Object.assign(params, { ...page }, from);
        }
        return await getSetListApi(params).then(res => {
            console.log(res)
            if (res.code == ResultEnum.SUCCESS) {
                let data = res.data;

        

				//权限02
                authArr.value= res.auth_list;
             
              
				//表格中带有操作列
				if(res.auth_list.editColor.show==false && res.auth_list.delColor.show==false ){
		
                    console.log('操作列置空')
						columnTypeAuth.length=0;
						
                        Object.assign(columnTypeAuth, []);
						
				}
				
                const { table_data, language } = data as { table_data: Record<string, any>; language: Record<string, any> };

                return table_data;
            }
        })

    };



    //表头信息
    const handleQueryColumns: MerakXTableInstance["queryColumns"] = async () => {
        return await getSetHeadApi().then(res => {
            if (res.code == ResultEnum.SUCCESS) {
                let data = res.data as MerakXTableQuery.Columns;
                // const { pageSize, columns } = data as { pageSize: number; columns: MerakXTableColumn[] };
                 console.log(data.columns)

				for (let index = 0; index < data.columns.length; index++) {
					const element = data.columns[index];
					if(element.field=="color_image"){

					
						element["slots"]={ default: `color` }
					}
					
				}

                state.columns = data.columns;

                return data;
            }
        })
    };
</script>

<style  lang="scss">

.el-tag {
  border: none;
  aspect-ratio: 1;
}
    .translation {
        height: 100%;


    }


     .el-color-dropdown__btns .el-button{
        padding:5px 10px !important;
        min-width:20px;
    }

    // :deep(.el-color-dropdown) {
    //     .el-button {
    //        padding:5px 10px;
    //     }
    // }

        


  
	.merak_modal{
    .form-box{

        .el-form-item {
          
        }
    }
}
</style>